package webbandidong.dao.impl;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
import webbandidong.dao.AdminDAO;
import webbandidong.model.Admin;
import webbandidong.util.Constant;
import webbandidong.util.CustomHibernateDaoSupport;

@Repository(value = "adminDAOImpl")
public class AdminDAOImpl extends CustomHibernateDaoSupport implements AdminDAO {

    public String checkExists(Admin admin) {

        Session session = null;
        Transaction transaction = null;
        
        try {
            session = getHibernateTemplate().getSessionFactory().openSession();
            transaction = session.beginTransaction();
            String hql = "from Admin where username = :username and password = :password";
            Query query = session.createQuery(hql);
            query.setParameter("username", admin.getUsername());
            query.setParameter("password", admin.getPassword());
            List admins = query.list();
            transaction.commit();
            return admins.isEmpty() ? "" : String.valueOf(((Admin)admins.get(0)).getId());
        }
        catch (Exception ex) {
            try {
                transaction.rollback();
            }
            finally {
                return Constant.ERROR;
            }
        }
        finally {
            if (session != null) {
                session.close();
            }
        }
    }

    public String updateAdmin(Admin admin) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = getHibernateTemplate().getSessionFactory().openSession();
            transaction = session.beginTransaction();
            session.update(admin);
            transaction.commit();
            return Constant.SUCCESS;
        }
        catch (Exception ex) {
            try {
                transaction.rollback();
            }
            finally {
                return Constant.ERROR;
            }
        }
        finally {
            if (session != null) {
                session.close();
            }
        }
    }
}
